#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <vector>
using namespace std;

/*-----------------------------------条件变量验证--------------------------------------*/

#define NUM 4
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

class ThreadData
{
public:
    ThreadData(int number,pthread_cond_t* cond)
    :_cond(cond)
    {
        _name = "thread-" + to_string(number);
    }
public:
    string _name;
    pthread_cond_t* _cond;
};

void* threadRun(void* arg)
{
    ThreadData* td = static_cast<ThreadData*>(arg);
    while(1)
    {   
        pthread_mutex_lock(&lock);
        cout << "now is " << td->_name << "run" << endl;
        pthread_cond_wait(td->_cond,&lock);     //本质上，让线程拿到锁后直接就释放锁，然后去排队等待被唤醒
        pthread_mutex_unlock(&lock);    
    }

    return nullptr;
}   

int main()
{
    vector<pthread_t> tids;
    vector<ThreadData*> tds;
    pthread_cond_t* cond = new pthread_cond_t;
    pthread_cond_init(cond, nullptr);

    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid = 0;
        ThreadData* td = new ThreadData(i,cond);
        pthread_create(&tid, nullptr, threadRun, td);
        tids.push_back(tid);
        tds.push_back(td);
    }

    sleep(3);
    cout << "main thread start signal..." << endl;
    while(1)
    {
        pthread_cond_signal(cond);      
        sleep(1);  
    }


    for(int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i],nullptr);
    }
    for(auto& e : tds)
    {
        delete e;
    }
    pthread_cond_destroy(cond);
    return 0;
}